/*
 * @LastEditTime: 2023-03-31 23:29:04
 * @Method: 
 * @Description: 
 */
package CodeTop;

public class Solution236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode l = lowestCommonAncestor(root.left, p, q);
        TreeNode r = lowestCommonAncestor(root.right, p, q);
        if (l != null && r != null) {
            return root;
        } else if (l == null && r != null) {
            return r;
        } else if (r == null && l != null) {
            return l;
        } else {
            return null;
        }
    }
}
